<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use App\Models\CustomerAppletsUserAlipay;
use App\Models\CustomerAppletsUserWechat;
use App\Models\MerchantStoreAppidSecret;
use Illuminate\Support\Facades\DB;
use App\Api\Controllers\CustomerApplets\BaseController;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use packages\umxnt\Watermark;
use WeixinApp\WXBizDataCrypt;

class CustomerAppletsUser extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected $table      = "customerapplets_users";
    protected $primaryKey = "id";

    protected $guard_name = 'customerApplets';

    protected $fillable = [
        'code',
        'store_id',
        'third_party_id',
        'user_source'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password','remember_token'
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getUserId();
    }


    /**
     * @return array
     */
    public function getUserId()
    {
        return [
            'type'     => 'customerAppletsUser',
            'id'       => $this->id,
            'store_id' => $this->store_id
        ];
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * 根据用户手机号判断用户的id哪些是同一用户
     * @param $store_id
     * @param $mobile
     * @return array|bool
     */
    public function getUserCollectId($store_id,$mobile){
        if(!isset($store_id) || empty($store_id)){
            return false;
        }
        if(!isset($mobile) || empty($mobile)){
            return false;
        }

        $user_id = [];

        $customerAppletsUserAliPayModel = new CustomerAppletsUserAlipay();
        $customerAppletsUserWeChatModel = new CustomerAppletsUserWechat();

        $customerAppletsUserAliPayResult = $customerAppletsUserAliPayModel->where(['store_id' => $store_id,'alipay_mobile' => $mobile])->first();
        $customerAppletsUserWeChatResult = $customerAppletsUserWeChatModel->where(['store_id' => $store_id,'wechat_mobile' => $mobile])->first();

        if(!empty($customerAppletsUserAliPayResult)){
            array_push($user_id,$customerAppletsUserAliPayResult->user_id);
        }

        if(!empty($customerAppletsUserWeChatResult)){
            array_push($user_id,$customerAppletsUserWeChatResult->user_id);
        }

        return $user_id;
    }

    /**
     * 获取用户基本信息
     * @param $user_id
     * @param $store_id
     * @return bool
     */
    public function getUserInfo($user_id,$store_id){
        if(!isset($user_id) || empty($user_id)){
            return false;
        }
        if(!isset($store_id) || empty($store_id)){
            return false;
        }

        $userStoreAuthor = $this->where(['id' => $user_id,'store_id' => $store_id])->first();

        return $userStoreAuthor;
    }

    /**
     * 请求微信接口获取用户手机号
     * @param $user_id
     * @param $store_id
     * @param $session_key
     * @param $encryptedData
     * @param $iv
     * @return array|bool
     */
    public function getUserMobile($user_id,$store_id,$session_key,$encryptedData,$iv){

        if(!isset($store_id) || empty($store_id)){
            return false;
        }
        if(!isset($user_id) || empty($user_id)){
            return false;
        }

        $merchantStoreAppIdSecretModel = new MerchantStoreAppidSecret();

        $merchantStoreAppIdSecretResult = $merchantStoreAppIdSecretModel->getStoreAppIdSecret($store_id);

        $appid = $merchantStoreAppIdSecretResult->wechat_appid;

        if(empty($appid)){
            return ["status" => 202 , "message" => "该门店的appid未设置"];
        }

        $encryptedData = urldecode($encryptedData);

        $mobile = new WXBizDataCrypt($appid,$session_key);

        $errCode = $mobile->decryptData($encryptedData,$iv,$data);

        if($errCode == 0){
            $data = json_decode($data,true);
            $mobile = $data['phoneNumber'];

            $result = DB::table("customerapplets_user_wechats")->where(['user_id' => $user_id,'store_id' => $store_id])->update([
                'wechat_mobile' => $mobile,
                'updated_at'    => date("Y-m-d H:i:s",time())
            ]);

            return ["status" => 200 , "message" => $mobile];
        }else{
            return ["status" => 202 , "message" => "获取失败"];
        }

    }

    /**
     * 查询用户微信/支付宝信息
     * @param $user_id
     * @param $store_id
     * @param $terminal_type
     * @return bool|int
     */
    public function getUserWeChatOrAliPayInfo($user_id,$store_id,$terminal_type){
        if(!isset($user_id) || empty($user_id)){
            return false;
        }
        if(!isset($store_id) || empty($store_id)){
            return false;
        }
        if(!isset($terminal_type) || empty($terminal_type)){
            return false;
        }

        //先判断用户是否在这个门店
        $userStoreAuthor = $this->where(['id' => $user_id,'store_id' => $store_id])->first();

        if(!$userStoreAuthor){
            return 405;
        }else{
            //判断用户是微信端请求还是支付宝端请求
            $base = new BaseController();
            $model = $base->weChatOrAliPayRequest($terminal_type);

            $userInfoResult = $model->getUserInfo($user_id,$store_id);
            return $userInfoResult;
        }
    }


    /**
     * 查寻用户在不在某一个门店中已经授权登录
     * @param $user_id
     * @param $store_id
     * @return bool
     */
    public function userStoreAuthorization($user_id,$store_id){
        if(!isset($user_id) || empty($user_id)){
            return false;
        }

        if(!isset($store_id) || empty($store_id)){
            return false;
        }

        $result = $this->where(['id' => $user_id , 'store_id' => $store_id])->first();
        if(!empty($result)){
            return true;
        }else{
            return false;
        }

    }
}
